package com.mecuros.auth.common.service.impl;

import com.mecuros.auth.common.model.SecurityUser;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yujianbo
 * @Classname JwtTokenUserDetailsService
 * @Description 从数据库中根据用户查询用户的详细信息
 * @Date 2022/4/25 9:49 下午
 */
@Service
public class JwtTokenUserDetailsService implements UserDetailsService {
    public static List<SecurityUser> userList = new ArrayList();

    static {
        SecurityUser admin = SecurityUser.builder()
                .username("admin")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .authorities(AuthorityUtils.createAuthorityList("ROLE_user", "ROLE_admin"))
                .build();

        SecurityUser user = SecurityUser.builder()
                .username("user")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .authorities(AuthorityUtils.createAuthorityList("ROLE_user"))
                .build();
        userList.add(admin);
        userList.add(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中查询
        List<SecurityUser> list = userList.stream()
                .filter(p -> username.equals(p.getUsername())).limit(1)
                .collect(Collectors.toList());

        if (Objects.isNull(list.get(0))){
            throw new UsernameNotFoundException("用户不存在");
        }
        return list.get(0);
    }
}
